package com.kehao.accountbook;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kehao.accountbook.adapter.ViewPagerAdapter;
import com.kehao.accountbook.fragment.ChartFragment;
import com.kehao.accountbook.fragment.HistoryAccountFragment;
import com.kehao.accountbook.fragment.MainFragment;
import com.kehao.accountbook.fragment.SettingFragment;
import com.kehao.accountbook.network.Network;
import com.kehao.accountbook.network.TwoCaseCallBack;
import com.kehao.accountbook.pojo.SimpleDate;
import com.kehao.accountbook.pojo.User;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final int NETWORK_BROKEN=1;
    private static final int NETWORK_SUCCESS=2;
    private static final String TAG = "MainActivity";

    private List<Fragment> fragments;
    private ImageView imgStar;
    private ImageView imgSetting;
    private ImageView imgChart;
    private ImageView imgHistory;
    private ViewPager viewPager;
    private ActionBar actionBar;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;

    private boolean rempwd;
    private String username;
    private String password;
    private Handler handler;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what){
                    case NETWORK_BROKEN:
                        //网络异常 如果距离登陆正常登录时间相差不超过3天进入离线模式
                        int x =3;
                        SimpleDate dateNow = new SimpleDate();
                        String beforestr = sharedPreferences.getString("lasttime","");
                        SimpleDate before = new SimpleDate(beforestr);
                        if(dateNow.getYear()-before.getYear()>1){//相差超过
                            startLoginActivity();
                        }else if(dateNow.getYear()-before.getYear()==1){//相差一年
                            if (dateNow.getMonth()!=1||before.getMonth()!=12){
                                startLoginActivity();
                            }else {
                                if (dateNow.getDay()+31-before.getDay()>x){
                                    startLoginActivity();
                                }
                            }
                        }else {//同年
                            if(dateNow.getMonth()-before.getMonth()>1){//相差超过一月
                                startLoginActivity();
                            }else if(dateNow.getMonth()-before.getMonth()==1){//相差一月
                                int monthday = SimpleDate.getMonthDay(before.getYear(),before.getMonth());
                                if(dateNow.getDay()+monthday-before.getDay()>x){
                                    startLoginActivity();
                                }
                            }else {//同月
                                if(dateNow.getDay()-before.getDay()>x){
                                    startLoginActivity();
                                }
                            }
                        }
                        getAccountApplication().setUsername(username);
                        if(fragments.get(0)!=null){
                            if(((MainFragment)fragments.get(0)).tv_mode!=null){
                                ((MainFragment)fragments.get(0)).tv_mode.setVisibility(View.VISIBLE);
                            }
                        }
                        break;
                    case NETWORK_SUCCESS:
                        if(fragments.get(0)!=null){
                            if(((MainFragment)fragments.get(0)).tv_mode!=null) {
                                ((MainFragment) fragments.get(0)).tv_mode.setVisibility(View.INVISIBLE);
                            }
                        }
                        break;
                }
            }
        };
    }

    private void init() {
        sharedPreferences = getSharedPreferences("data",MODE_PRIVATE);
        actionBar = getSupportActionBar();
        actionBar.hide();
        imgStar = findViewById(R.id.img_star);
        imgHistory = findViewById(R.id.img_history);
        imgChart = findViewById(R.id.img_chart);
        imgSetting = findViewById(R.id.img_setting);
        Intent intentGet = getIntent();
        //首次启动跳转到登录界面(还未登录)
        if(getAccountApplication().isLoginstatus() == false){
            rempwd = sharedPreferences.getBoolean("rempwd",false);
            username = sharedPreferences.getString("username","");
            password = sharedPreferences.getString("password","");
            getAccountApplication().setRempwd(rempwd);
            if(rempwd){//记住了密码
                if((!username.equals(""))&&(!password.equals(""))&&rempwd){
                    User user = new User(username,password);
                    String json =new Gson().toJson(user);
                    getAccountApplication().setUsername(username);
                    Network network = new Network(new TwoCaseCallBack() {
                        @Override
                        public void success(String string) {//网络正常
                            if(string.equals("ok")){//登陆成功
                                getAccountApplication().setLoginstatus(true);
                                getAccountApplication().setUsername(username);
                                getAccountApplication().setPassword(password);
                                editor = sharedPreferences.edit();
                                editor.putString("lasttime",new SimpleDate().toString());
                                editor.apply();
                                SimpleDate simpleDate = new SimpleDate();
                                getAccountApplication().syncData(simpleDate.getYear(),simpleDate.getMonth());
                            }else if (string.equals("fail")){//账号密码错误 转到登陆界面
                                startLoginActivity();
                            }
                        }
                        @Override
                        public void fail() {//网络失败
                            Message message = new Message();
                            message.what = NETWORK_BROKEN;
                            handler.sendMessage(message);
                        }
                    },json,Network.LOGIN_URL,getAccountApplication());
                    network.send();
                }
            }else {
                //没有记住密码
                startLoginActivity();
            }
        }else {//从登陆界面登录成功后
            editor = sharedPreferences.edit();
            editor.putString("lasttime",new SimpleDate().toString());
            editor.apply();
            SimpleDate simpleDate = new SimpleDate();
            getAccountApplication().syncData(simpleDate.getYear(),simpleDate.getMonth());
        }
        fragments = new ArrayList<Fragment>();
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(),fragments);
        fragments.add(new MainFragment());
        fragments.add(new HistoryAccountFragment());
        fragments.add(new ChartFragment());
        fragments.add(new SettingFragment());
        viewPager = findViewById(R.id.vp);
        viewPager.setAdapter(viewPagerAdapter);
        viewPager.setCurrentItem(0);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                changeIcon(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void startLoginActivity() {
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    private void changeIcon(int i){
        imgStar.setImageResource(R.drawable.star_light);
        imgHistory.setImageResource(R.drawable.history_light);
        imgChart.setImageResource(R.drawable.chart_light);
        imgSetting.setImageResource(R.drawable.setting_light);
        switch (i){
            case 0:
                imgStar.setImageResource(R.drawable.star_dark);
                break;
            case 1:
                imgHistory.setImageResource(R.drawable.history_dark);
                break;
            case 2:
                imgChart.setImageResource(R.drawable.chart_dark);
                break;
            case 3:
                imgSetting.setImageResource(R.drawable.setting_dark);
                break;
        }
    }


    public void onClickStar(View view) {
        changeIcon(0);
        viewPager.setCurrentItem(0);
    }

    public void onClickSetting(View view) {
        changeIcon(3);
        viewPager.setCurrentItem(3);
    }

    public void onClickHistory(View view) {
        changeIcon(1);
        viewPager.setCurrentItem(1);
    }
    public void onClickChart(View view) {
        changeIcon(2);
        viewPager.setCurrentItem(2);
    }

    public List<Fragment> getFragments() {
        return fragments;
    }

    private AccountApplication getAccountApplication(){
        return (AccountApplication)getApplication();
    }


}
